<?php

/*
	This file is part of Mandragon.

    Mandragon is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Mandragon is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Mandragon.  If not, see <http://www.gnu.org/licenses/>.
*/

include_once('sys/regionfunctions.inc');

class SearchPage {
	
	private $alerter;
	
	public function __construct() {
		$this->alerter = new Alerter();
	}

	/**
	 * adds extra access checks, dependent on page state
	 */
	function page_inc_check_access($page) {
		check_access("READ");
	}

	function page_inc_execute_action($page, $action) {
		$THISDIR = $page->directory_tree[$page->dir_depth-1];

		switch($action) {
			default:
				$this->alerter->add_alert("unknown action: $action");
				break;
		}
	}

	/**
	 * execute page logic
	 */
	function page_inc_execute($page) {
		global $CONFIG;
		$CONTENT = array();
		$THISDIR = $page->directory_tree[$page->dir_depth-1];
		
		$CONTENT['title'] = "Zoeken - {$THISDIR['title']}";

		$inputs = array();
		$creator = new FormCreator();	
		$inputs[] = $creator->header("Zoeken");
		$inputs[] = $creator->input_field("Zoeken naar", "q", $_GET['q']);
		$inputs[] = $creator->info("Zoektermen scheid je met spaties. Woordcombinaties kan je met aanhalingstekens omringen (bv. <a href=?q=" . urlencode('barbecue "gebraden speenvarken"') . "><i>barbecue \"gebraden speenvarken\"</i></a>).");
		if (($_GET['type'] != "ad") and ($_GET['type'] != "advanced"))
			$inputs[] = $creator->input_radio("", "bot", array('mdg', 'google', 'web'), array('mandragon zoekrobot', 'google op mandragon', 'google op het web'), $_GET['bot'] ? $_GET['bot'] : 'mdg');
		$inputs[] = $creator->input_select("", "type", array('plain', 'advanced', 'ad', 'not'), array('gewoon zoeken', 'geavanceerd zoeken', 'advertenties zoeken', 'niet zoeken'), '', $_GET['type'] ? $_GET['type'] : 'plain', 'document.searchform.submit()');
		
		if ($_GET['type'] == "ad") {
			$inputs[] = $creator->header("Advertenties");
			$inputs[] = $creator->input_select("Soort advertentie", "seek", array('ALL', 'GZ', 'TK'), array('alles', 'gezocht', 'te koop aangeboden'), '', $_GET['seek'] ? $_GET['seek'] : 'ALL');
			$game_types = get_keys_and_values("game_type_id", "game_type", "GAME_TYPE");
			$game_types['keys'][] = "ALL";
			$game_types['values'][] = "alles zoeken";
			$inputs[] = $creator->input_select("Soort spel", "game_type_id", $game_types['keys'], $game_types['values'], "", $_GET['game_type_id'] ? $_GET['game_type_id'] : "ALL");
			$inputs[] = $creator->input_field("Spel", "game", $_GET['game']);
			$inputs[] = $creator->info("Laat blanco indien gelijk.");
			$kv = region_get_regions_kv();
			$inputs[] = $creator->input_select("Regio", "region_id", array_merge(array("ALL"), $kv['keys']), array_merge(array("overal zoeken"), $kv['values']), "", $_GET['region_id'] ? $_GET['region_id'] : "ALL");
			$inputs[] = $creator->info("Advertenties uit mandragon II of eerder (voor 15 februari 2005) worden niet doorzocht wanneer hierboven verdere specificaties worden opgelegd");
		} else if ($_GET['type'] == "advanced") {
			$inputs[] = $creator->header("Geavanceerd");
			list($keys, $vals) = generate_list(0, 0, array(), array(), $page->menu);
			$keys[] = "ALL";
			$vals[] = "overal zoeken";
			$inputs[] = $creator->input_select("Zoeken in", "dir_id", $keys, $vals, "", $_GET['dir_id'] ? $_GET['dir_id'] : "ALL");
			$inputs[] = $creator->input_select("Tijdstip", "timed", array('NO', 'before', 'after', 'between'), array('alles zoeken', 'voor tijdstip', 'na tijdstip', 'tussen'), '', $_GET['timed'] ? $_GET['timed'] : 'NO', 'document.searchform.submit()');
			if (($_GET['timed'] == 'before') or ($_GET['timed'] == 'between'))
				$inputs[] = $creator->input_date("Voor", "before");
			if (($_GET['timed'] == 'after') or ($_GET['timed'] == 'between'))
				$inputs[] = $creator->input_date("Na", "after");
			$inputs[] = $creator->input_field("Geplaatst door", "author", $_GET['author']);
			$inputs[] = $creator->info("Laat blanco indien gelijk.");
		}
		
		$CONTENT['searchform'] = $creator->create("searchform", array_reverse($inputs), "", "GET");

		if ($_GET['submitted']) {
		
			$start = getmicrotime();
		
			if ($_GET['type'] == "NO")
				return;
				
			if ($_GET['bot'] == "web")
				redirect("http://www.google.be/search?hl=nl&q=" . stripslashes($_GET['q']));
			else if ($_GET['bot'] == "google")
				redirect("http://www.google.be/search?hl=nl&q=site:www.mandragon.be+". stripslashes($_GET['q']));
			
			if (!$_GET['q'])
				return;
			
			$qarr = explode('"', " " . ereg_replace("'", "\'", ereg_replace(",", "", stripslashes($_GET['q']))));
			reset($qarr);
			//$expr = "";
			$exprarr = array();
			do {
				$t = current($qarr);
				if ($inside) {
					$exprarr[] = array('type' => "LIKE", 'str' => trim(addslashes($t)));
				} else {
					$exprarr[] = array('type' => "MATCH", 'str' => trim(addslashes($t)));
				}
				$inside = 1 - $inside;
			} while (next($qarr));
			
			// look for posts first
			$posts = db_do_query($page, db_query_select(array(array(), "item_id, body"), array("POST INNER JOIN POST_BODY ON POST.post_id = POST_BODY.post_id", "DUMMY"), where_clause_col($exprarr, "title") . " AND " . where_clause_col($exprarr, "body")));
			
			$poststr = "-1";
			$post_bodies = array();
			if (db_num_rows($posts) > 0)
				while ($p = db_fetch_array($posts)) {
					$poststr .= ",{$p['item_id']}";
					$post_bodies[$p['item_id']] = $p['body'];
				}
			
			$where = "!ITEM.deleted AND (\n";
				$where .= "ITEM.item_id IN ($poststr)";
				$where .= " OR " . where_clause_col($exprarr, "ITEM.title");
				$where .= " OR " . where_clause_col($exprarr, "AD.body");
			if ($_GET['type'] != "ad") {
				$where .= " OR " . where_clause_col($exprarr, "ARTICLE.body");
				$where .= " OR " . where_clause_col($exprarr, "DOWNLOAD.body");
				$where .= " OR " . where_clause_col($exprarr, "NEWS.body");
				$where .= " OR " . where_clause_col($exprarr, "LINK.body");
				$where .= " OR " . where_clause_col($exprarr, "GALLERY.body");
				$where .= " OR " . where_clause_col($exprarr, "POLL.body");
			}
			$where .= "\n)";
			
			if (($_GET['timed'] == 'before') or ($_GET['timed'] == 'between'))
				if (check_date_valid($_GET['before_day'], $_GET['before_month'], $_GET['before_year'], "datum 'voor'"))
					$where .= " AND ITEM.creation < " . $_GET['before_year'] . (($_GET['before_month'] > 9) ? "{$_GET['before_month']}" : "0{$_GET['before_month']}") . (($_GET['before_day'] > 9) ? "{$_GET['before_day']}" : "0{$_GET['before_day']}") . "000000 \n";
			if (($_GET['timed'] == 'after') or ($_GET['timed'] == 'between'))
				if (check_date_valid($_GET['after_day'], $_GET['after_month'], $_GET['after_year'], "datum 'na'"))
					$where .= " AND ITEM.creation > " . $_GET['after_year'] . (($_GET['after_month'] > 9) ? "{$_GET['after_month']}" : "0{$_GET['after_month']}") . (($_GET['after_day'] > 9) ? "{$_GET['after_day']}" : "0{$_GET['after_day']}") . "000000 \n";
				
			if ($_GET['author'])
				$where .= " AND nick LIKE '{$_GET['author']}'";
			
			if ($_GET['type'] == "ad")
				$items = db_do_query($page, db_query_select(array(array(), "ITEM.*, extension, MEMBER.nick AS author_nick, AD.game_id, AD.region_id, AD.seek, AD.body AS body_ad"), array("((ITEM INNER JOIN ITEM_TYPE ON ITEM.item_type_id = ITEM_TYPE.item_type_id)\n INNER JOIN MEMBER ON ITEM.author = MEMBER.user_id)\n LEFT JOIN AD ON ITEM.item_id = AD.item_id", "DUMMY"), $where));
			else
				$items = db_do_query($page, db_query_select(array(array(), "ITEM.*, extension, MEMBER.nick AS author_nick, AD.body AS body_ad, ARTICLE.body AS body_article, NEWS.body, POLL.body AS body_poll, GALLERY.body AS body_gallery, LINK.body AS body_link"), array("((((((((ITEM INNER JOIN ITEM_TYPE ON ITEM.item_type_id = ITEM_TYPE.item_type_id)\n INNER JOIN MEMBER ON ITEM.author = MEMBER.user_id)\n LEFT JOIN ARTICLE ON ITEM.item_id = ARTICLE.item_id)\n LEFT JOIN AD ON ITEM.item_id = AD.item_id)\n LEFT JOIN DOWNLOAD ON ITEM.item_id = DOWNLOAD.item_id)\n LEFT JOIN NEWS ON ITEM.item_id = NEWS.item_id)\n LEFT JOIN LINK ON ITEM.item_id = LINK.item_id)\n LEFT JOIN GALLERY ON ITEM.item_id = GALLERY.item_id)\n LEFT JOIN POLL ON ITEM.item_id = POLL.item_id", "DUMMY"), $where));
			
			if ($_GET['type'] == "ad") {
				$games = game_get_games();
				$game_types = get_keyed_values("game_type_id", "game_type", "GAME_TYPE");
				$regions = region_get_regions();
			}
			
			$itemids = "-1";
			$item_array = array();
			if (db_num_rows($items))
				while ($item = db_fetch_array($items)) {
					if ($_GET['type'] == "ad") {
						if ($_GET['game_type_id'] != "ALL") {
							if (($item['extension'] != "ad") or !$item['game_id'])
								continue;
							$target_type = $game_types[$_GET['game_type_id']];
							if (!eregi($target_type, implode(" ", $games[$item['game_id']]['types'])))
								continue;
						}
						if ($_GET['region_id'] != "ALL") {
							if (($item['extension'] != "ad") or !$item['region_id'])
								continue;
							if (!region_is_inside($item['region_id'], $_GET['region_id'], $regions))
								continue;
						}
						if ($_GET['game']) {
							if (!eregi($_GET['game'], $item['title'])) {
								if (($item['extension'] != "ad") or !$item['game_id'])
									continue;
								if (!eregi($_GET['game'], $games[$item['game_id']]['name']))
									continue;
							}
						}
						if ($_GET['seek'] != "ALL") {
							if ($item['extension'] == "ad") {
								if ($item['seek'] and ($_GET['seek'] != "GZ"))
									continue;
								if (!$item['seek'] and ($_GET['seek'] == "GZ"))
									continue;
							} else if (!eregi("^{$_GET['seek']}", $item['title']))
								continue;
						}
					}
					$item['body'] = $item["body_{$item['extension']}"];
					$tiem['post'] = $post_bodies[$item['item_id']];
					$item_array[$item['item_id']] = $item;
					$itemids .= ",{$item['item_id']}";
				}
			
			$results = array();
		
			$where = "NOT ITEM_IN.deleted AND item_id IN ({$itemids})";
			
			if ($_GET['dir_id'] and ($_GET['dir_id'] != "ALL"))
				$where .= "\n AND ((dir_id = {$_GET['dir_id']}) OR (parent_id = {$_GET['dir_id']}))";

			$item_occurences = array();
			$occurences = db_do_query($page, db_query_select(array(array(), "SUBSET.sub_title, SUBSET.sub_id, SUB_IN.dir_id, ITEM_IN.item_id"), array("((ITEM_IN INNER JOIN SUB_IN ON ITEM_IN.sub_id = SUB_IN.sub_id) INNER JOIN SUBSET ON SUB_IN.sub_id = SUBSET.sub_id) LEFT JOIN DIRECTORY_TREE ON SUB_IN.dir_id = DIRECTORY_TREE.child_id", "DUMMY"), $where));
			if (db_num_rows($occurences) > 0) {
				while ($occ = db_fetch_array($occurences)) {
					$occarr = array();
					$dir = $occ['dir_id'];
					$link = "";
					$deny = 0;
					while (($dir != 0) and !$deny) {
						if ($page->menu[$dir]['access'] == "DENY")
							$deny++;
						array_unshift($occarr, array('name' => $page->menu[$dir]['menuname'], 'link' => $page->menu[$dir]['name']));
						$dir = $page->menu[$dir]['parent_id'];
					}
					if (!$deny) {
						$occarr[] = array('name' => $occ['sub_title'] ? $occ['sub_title'] : "Andere..", 'link' => "{$occ['sub_id']}.subset");
						if ($occ['item_id'] == $prev_item) {
							$old = array_pop($item_occurences);
							$item_occurences[] = array('item' => $occ['item_id'], 'occs' => array_merge($old['occs'], array($occarr)));
						} else
							$item_occurences[] = array('item' => $occ['item_id'], 'occs' => array($occarr));
						$prev_item = $occ['item_id'];
					}
				}
			
				reset($item_occurences);
				do {
					$o = current($item_occurences);
					$results[] = array('item' => $item_array[$o['item']], 'occs' => $o['occs']);
				} while (next($item_occurences));
			}
			
			$CONTENT['results'] = array('r' => $results, 's' => (round(getmicrotime() - $start, 3)), 'q' => $_GET);
			
		}
		
		$page->content = $CONTENT;
	}

	/**
	 * dress up page content using skin stuff
	 */
	function page_inc_dress($page) {
		print_form($page, $page->content['searchform']);
		if ($_GET['submitted'])
			print_searchresults($page->content['results']);
	}

	function generate_list($parent, $level, $keys, $vals, $menu) {
		$rank = 0;	
		$space = "";
		for ($i = 0; $i < $level; $i++)
			$space .= "&nbsp;&nbsp;&nbsp;&nbsp;";
		while ($id = @array_shift($menu[$parent]['children'])) {
			if ($menu[$id]['access'] != "DENY") {
				array_push($keys, "$id");
				array_push($vals, $space . $menu[$id]['menuname']);
				list($keys, $vals) = generate_list($id, ($level+1), $keys, $vals, $menu);
			}
		}	
		return array($keys, $vals);
	}

	function where_clause_col($exprarr, $column) {
		reset($exprarr);
		$where = "(0";
		do {
			$e = current($exprarr);
			if ($e['type'] == "LIKE" or strlen($e['str']) < 4)
				$where .= "\nOR $column LIKE '%{$e['str']}%'";
			else
				$where .= "\nOR (MATCH($column) AGAINST ('{$e['str']}'))";
		} while (next($exprarr));
		$where .= ")";
		return $where;
	}
}

?>
